from collections import defaultdict

colours = (
    ("Y", 'yellow'),
    ("Ali", 'Blue'),
    ("Arham", 'Green'),
    ("Ali", 'Black'),
    ("Y", 'Red'),
    ("A", 'Silver'),
)
favourite_colours = defaultdict(list)
for name, colour in colours:
    favourite_colours[name].append(colour)  #同样key的键值会归到一类
print(favourite_colours)

print("出发KeyError")
# some_dict = {}
# some_dict['colours']['favourite'] = "yellow"
print("解决方法")
import collections

tree = lambda: collections.defaultdict(tree)
some_dict = tree()
some_dict['colours']['favourite'] = "yellow"

import json

print(json.dumps(some_dict))

print("counter test")
from collections import Counter

favs = Counter(name for name, colour in colours)
print(favs) #统计列表等，里面的元素出现次数

print("统计文件的行数")
# with open('filename', 'rb') as f:
#     line_count = Counter(f)
# print(line_count)

print("deque 双向队列 test")
from collections import deque

d = deque()
d.append('1')
d.append('2')
d.append('3')
print(len(d))
print(d[-1])
d = deque(range(5))
d.popleft()
d.pop()
print(d)
d = deque(maxlen=30)
d = deque([1,2,3,4])
d.extend([6,7,8])
d.extendleft([0])
print(d)

print("namedtuple test")
from collections import namedtuple

Animal = namedtuple("Animal", 'name age type')
perry = Animal(name = "perry", age= 31, type="cat")
print(perry)
print(perry.name)
print(perry[0])
print(perry._asdict())

print("Enum test")
from collections import namedtuple
from enum import Enum


class Species(Enum):
    cat = 1
    dog = 2
    horse = 3
    aardvark = 4
    butterfly = 5
    owl = 6
    platypus = 7
    dragon = 8
    unicorn = 9

    kitten = 1
    puppy = 2
Animal = namedtuple('Animal', 'name age type')
perry = Animal(name="Petty", age = 31, type=Species.cat)
drogon = Animal(name="Drogon", age = 4, type=Species.dragon)
tom = Animal(name='Tom', age=75, type=Species.cat)
charlie = Animal(name="Charlie", age=2, type=Species.kitten)
print(charlie.type == tom.type)
print(charlie.type)

print("访问枚举元素")
print(Species(1))
print(Species['cat'])
print(Species.cat)
